const fs = wx.getFileSystemManager()//全局文件管理器
const app = getApp();//获取全局APP实例
const xlsx = require('../lib/xlsx.core.min.js')//引入xlsx读取包
const MD5 = require('./md5.js')
const xml2js = require('xml2js');

/**
 * 封装微信Promise解决微信异步函数回调地狱
 */
const wxPromisify = (fn) => {
  return (obj = {}) => {//设置对象的默认值
    return new Promise((resolve,reject) => {
      //Promise就是回调替换管理器，他负责把原来异步函数中的异步操作，替换成成功和失败的回调(古老的方式的回调)
      //并且把这个回调放入Promise对象中，最后返回的是一个异步操作的Promise对象，他拥有了这些异步操作的回调，
      //自身的.then属性来依次调用回调（当前也有可能不是按参数顺序），然后再把替换过的对象重新给这个函数塞进去（封装的思想）
      //然后我们就成功管理起了这些回调，方便了调用
      obj.success = function (res) {
        resolve(res)
      }
      obj.fail = function (res) {
        reject(res)
      }
      fn(obj)//执行函数参数为传入函数的参数
    })
  }
}

/**
 * 通过下载文件的路径读取Excel
 */
const readExcelToJsonSync = (url,index = '0') => {
  const fileData = fs.readFileSync(url, 'binary')//读取编码
  const workbook = xlsx.read(fileData, {
    type: 'binary'//因为无法直接操作文件所以需要得到微信文件管理读取到的二进制文件
  })
  const sheetNames = workbook.SheetNames;
  const data = xlsx.utils.sheet_to_json(workbook.Sheets[sheetNames[index]])
  return data
}
/**
 * 通过网络请求读取excel数据，避免下载
 */
const requestExcelToJson = (url, index = '0') => {
  const request = wxPromisify(wx.request)
  return request({
    url: url,
    responseType: 'arraybuffer'//返回的二进制缓冲数组
  }).then(res => {
    const workbook = xlsx.read(res.data, {
      type: 'buffer'//指定数据的类型也是缓冲数组
    })
    const sheetNames = workbook.SheetNames;
    const data = xlsx.utils.sheet_to_json(workbook.Sheets[sheetNames[0]])
    return new Promise((resolve, reject) => {
      resolve(data)
    })
  })
}
/**
 * 查找对应的数据中匹配
 */
const findEqual = (datas,attr,equalStr) =>{
  for(let data of datas){

    //Excel比较项
    if(data[attr] + '' === equalStr + ''){
      return data
    }
  }
}
const findforRegExp = (datas,attr,equalStr) => {
  return datas.filter(function (e) {
    return e[attr].indexOf(equalStr) >= 0
  })
}
/**
 * 下载文件
 */
const downloadExcel = (name,callback) => {
  wx.downloadFile({
    url: app.globalData.domain + name,
    success: (res) => {
      callback(res)
    },
    fail: (res) => {
      callback(res)
    }
  })
}
//分割字符串函数
const getHilightStrArray =  function (str, key) {
  return str.replace(new RegExp(`${key}`, 'g'), `%%${key}%%`).split('%%');
}

const generatePreOrder = function(openid,pay,callback){
  const request = wxPromisify(wx.request)
  const builder = new xml2js.Builder({ rootName:'xml'});
  const { appid, mch_id, pre_order_api, mch_key: key, notify_url,ip_api} = app.globalData
  const nonce_str = Math.random().toString(36).substr(2)
  const out_trade_no = generateOrderNum()
  let spbill_create_ip = ''
  request({
    url: ip_api
  }).then(res => {
    const ipObj = JSON.parse(res.data.split("=")[1].replace(";","").trim())
    const spbill_create_ip = ipObj.cip
    // console.log(res.data.query)
    let pramStr = 'appid=' + appid + '&body=跟我游展馆-使用缴费' + '&mch_id=' + mch_id +
      '&nonce_str=' + nonce_str + '&notify_url=' + notify_url + '&openid=' + openid +
      '&out_trade_no=' + out_trade_no + '&spbill_create_ip=' + spbill_create_ip + '&total_fee=' + pay +
      '&trade_type=JSAPI'
    let pramStrTemp = pramStr + '&key=' + key
    const sign = MD5.hash(pramStrTemp).toUpperCase()
    const data = {
      appid,
      body: '跟我游展馆-使用缴费',
      mch_id,
      nonce_str,
      notify_url,
      openid,
      out_trade_no,
      spbill_create_ip,
      total_fee: pay,
      trade_type: 'JSAPI',
      sign
    }
    request({
      url: pre_order_api,
      data: builder.buildObject(data),
      method: 'POST',
    }).then(res => {
      console.log(res)
      xml2js.parseString(res.data, (err, result) => {
        // console.log(result)
        const resObj = {
          appid,
          nonceStr: nonce_str,
          prepay_id: result.xml.prepay_id[0],
          key
        }
        callback(resObj)
      });

    })
  })

}
const generateOrderNum = function(){
  let randstr = ('000000' + Math.floor(Math.random() * 999999)).slice(-6);
  return dateFtt('yyyyMMddhhmmss', new Date()) + randstr
}
const dateFtt = function (fmt, date) { //author: meizz 
  var o = {
    "M+": date.getMonth() + 1,     //月份 
    "d+": date.getDate(),     //日 
    "h+": date.getHours(),     //小时 
    "m+": date.getMinutes(),     //分 
    "s+": date.getSeconds(),     //秒 
    "q+": Math.floor((date.getMonth() + 3) / 3), //季度 
    "S": date.getMilliseconds()    //毫秒 
  };
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt))
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;
}


module.exports = {
  readExcelToJsonSync: readExcelToJsonSync,
  findEqual: findEqual,
  downloadExcel: downloadExcel,
  requestExcelToJson: requestExcelToJson,
  wxPromisify: wxPromisify,
  findforRegExp: findforRegExp,
  getHilightStrArray: getHilightStrArray,
  generatePreOrder: generatePreOrder
}

